package com.example.mybaties.testone.controller;

import com.example.mybaties.testone.domain.SysDict;
import com.example.mybaties.testone.service.SysDictService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/sysdict")
public class SysDictController {

    private Logger logger = LogManager.getLogger(SysDictController.class);

    @Resource
    private SysDictService sysDictService;

    @RequestMapping(value = "/showdictlist.action")
    public String showDictList(Model model, HttpServletRequest request){
        List<SysDict> sysdicts = sysDictService.selectAll();
        model.addAttribute("sysdicts", sysdicts);
        //request.setAttribute("sysdicts", sysdicts);
        logger.debug("sysdicts = " + sysdicts);
        return "sysdictlist";
    }

    /**
     * 在列表页面点击编辑按钮之后会执行该方法
     */
    @RequestMapping(value = "/showEidt.action", method = RequestMethod.GET)
    public String showEidt(Long id, Model model){
        logger.debug("id = " + id);
        SysDict sysDict = sysDictService.selectSysDictById(id);
        model.addAttribute("sysDict", sysDict);
        return "sysdict_edit";
    }

    /**
     * 保存或者更新字典
     */
    @RequestMapping(value = "/saveOrEdit.action", method = RequestMethod.POST)
    public String saveOrEdit(SysDict sysDict){
        logger.debug(sysDict);
        boolean isSuccess = sysDictService.saveOrUpdate(sysDict);
        if(isSuccess){
            return "redirect:/sysdict/showdictlist.action";
        }else{
            return "failure";
        }
    }

    @RequestMapping(value = "/deleteById.action")
    public String deleteById(Long id){
        boolean isSuccess = sysDictService.deleteById(id);
        if(isSuccess){
            return "redirect:/sysdict/showdictlist.action";
        }else{
            return "failure";
        }
    }

    public void setSysDictService(SysDictService sysDictService) {
        this.sysDictService = sysDictService;
    }
}
